package quartz.demo.controller;

import org.quartz.SchedulerException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import quartz.demo.entity.QuartzBean;
import quartz.demo.service.QuartzService;

import javax.annotation.Resource;

@RestController
@RequestMapping("/quartz")
public class QuartzController {

    @Resource
    private QuartzService quartzService;


    /**
    * @Description: 立即执行一次
    * @Date: 2023-04-17 14:33:09
    * @Author: 陈文波
    */
    @GetMapping(value = "/execute")
    public String execute() {
        // 可以根据实际情况进行查询，这里固定查询id=1的数据
        QuartzBean quartzBean = quartzService.getById(1);
        if (quartzBean == null) {
            return "未找到对应实体";
        }
        try {
            quartzService.execute(quartzBean);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "执行一次成功";
    }

    /**
    * @Description: 启动定时任务，quartz任务开启
    * @Date: 2023-04-17 14:33:47
    * @Author: 陈文波
    */
    @GetMapping("/beginExecute")
    public String beginExecute(){
        quartzService.beginExecute();
        return "定时任务启动成功";
    }

    /**
    * @Description: 暂停定时任务，quartz任务停止
    * @Date: 2023-04-17 14:33:56
    * @Author: 陈文波
    */
    @GetMapping("/pause")
    public String pause(){
        QuartzBean quartzBean = quartzService.getById(1);
        if (quartzBean == null) {
            return "定时任务不存在";
        }
        quartzService.pause(quartzBean);
        return "定时任务暂停成功";
    }

    /**
    * @Description: 修改定时任务，如果为开启状态：添加quartz任务，如果为停止状态：删除quartz任务
    * @Date: 2023-04-17 15:56:38
    * @Author: 陈文波
    */
    @PostMapping("/update")
    public String update() throws SchedulerException {
        QuartzBean quartzBean = quartzService.getById(1);
        if (quartzBean == null) {
            return "定时任务不存在";
        }
        quartzService.updateJob(quartzBean);

        return "修改定时任务成功";
    }

    /**
    * @Description: 删除定时任务，任务quartz停止
    * @Date: 2023-04-17 15:58:55
    * @Author: 陈文波
    */
    @PostMapping("/delete")
    public String delete(){
        quartzService.delete(1);
        return "删除定时任务成功";
    }

    /**
    * @Description: 添加定时任务，如果状态为开启状态：任务quartz开启，如果状态为停止状态：任务quartz关闭
    * @Date: 2023-04-17 16:00:19
    * @Author: 陈文波
    */
    @PostMapping("/add")
    public String add(){
        QuartzBean quartzBean = quartzService.getById(1);
        quartzService.add(quartzBean);
        return "添加定时任务";
    }





}
